from django.utils import simplejson
from django.http import HttpResponse
from django.contrib.auth.models import User
from qbank.models import course
from qbank.models import dialog
from qbank.models import quesAns
from qbank.models import userView
from qbank.models import userBkView
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def usersView_json(request):
	"""Sends or accepts the list of couplets already viewed by the current logged in user"""
	user = request.user
	
	if request.method == "GET":
		uvArray = []
		uvList = userView.objects.filter(userId=user)
		uvArray.append({"Total count":uvList.count()})
		for uv in uvList.all():
				uvArray.append({"dialogId":uv.dialog.id, "coupletId":uv.quesAns.id, "studentRating":uv.studentRating, "timesViewed": uv.timesViewed})
	
		response = HttpResponse(simplejson.dumps(uvArray),mimetype='application/json')
		response['Content-Disposition'] = 'filename=UsersView.json' 
		return response
	elif request.method == "POST":
		items = simplejson.loads(request.raw_post_data)
		for item in items:
			d = dialog.objects.get(id=item['dialogId'])
			q = d.quesans_set.get(id=item['coupletId'])
			uv, created = userView.objects.get_or_create(userId=user, dialog=d, quesAns=q)
			if item.has_key('studentRating'): uv.studentRating = item['studentRating']
			if item.has_key('timesViewed'): uv.timesViewed = item['timesViewed']
			uv.save()
		return HttpResponse()	

@csrf_exempt
def usersBookmark_json(request):
	"""Sends or accepts the bookmarked couplet for the current logged in user"""
	user = request.user
	
	if request.method == "GET":
		ubArray = []
		ubList = userBkView.objects.filter(userId=user)
		ubArray.append({"Total count":ubList.count()})
		for ub in ubList.all():
				ubArray.append({"dialogId":ub.dialog.id, "coupletId":ub.quesAns.id, "last_diffFilter":ub.last_diffFilter})
	
		response = HttpResponse(simplejson.dumps(ubArray),mimetype='application/json')
		response['Content-Disposition'] = 'filename=UserBookmarkView.json' 
		return response
	elif request.method == "POST":
		items = simplejson.loads(request.raw_post_data)
		for item in items:
			d = dialog.objects.get(id=item['dialogId'])
			q = d.quesans_set.get(id=item['coupletId'])
			ub, created = userBkView.objects.get_or_create(userId=user, dialog=d, defaults={'quesAns': q})
			ub.quesAns = q
			ub.save()
		return HttpResponse()

